<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 19-3-6
 * Time: 下午2:29
 */

namespace common\components\icbcapi\sdk;



class RSA
{
    public static function sign($content,$privateKey,$algorithm){
        $privateKey = "-----BEGIN PRIVATE KEY-----
{$privateKey}
-----END PRIVATE KEY-----";
//        $pri_id = openssl_pkey_get_private($privateKey);
//        $pri_key_id = openssl_get_privatekey($pri_id);
        $pri_key_id = $privateKey;
        if(IcbcConstants::$SIGN_SHA1RSA_ALGORITHMS == $algorithm){
            openssl_sign($content,$signature,$pri_key_id, OPENSSL_ALGO_SHA1);
        }elseif (IcbcConstants::$SIGN_SHA256RSA_ALGORITHMS == $algorithm) {
            openssl_sign($content,$signature,$pri_key_id, OPENSSL_ALGO_SHA256);
        }else{
            throw new \Exception("Only support OPENSSL_ALGO_SHA1 or OPENSSL_ALGO_SHA256 algorithm signature!");
        }
        $sign =  base64_encode($signature);
//        openssl_free_key($pri_key_id);
        return $sign;
    }

    public static function verify($content,$signature,$publicKey,$algorithm){
        if(IcbcConstants::$SIGN_SHA1RSA_ALGORITHMS == $algorithm){
            return openssl_verify($content,base64_decode($signature),"-----BEGIN PUBLIC KEY-----\n".$publicKey."\n-----END PUBLIC KEY-----", OPENSSL_ALGO_SHA1);
        }elseif (IcbcConstants::$SIGN_SHA256RSA_ALGORITHMS == $algorithm) {
            return openssl_verify($content,base64_decode($signature),"-----BEGIN PUBLIC KEY-----\n".$publicKey."\n-----END PUBLIC KEY-----", OPENSSL_ALGO_SHA256);
        }else{
            throw new \Exception("Only support OPENSSL_ALGO_SHA1 or OPENSSL_ALGO_SHA256 algorithm signature verify!");
        }
    }
}